package com.xwj.service.impl;

import com.xwj.dao.OrderMapper;
import com.xwj.domain.Order;
import com.xwj.dto.CommonResult;
import com.xwj.enums.ResultCode;
import com.xwj.feign.StorageFeignClient;
import com.xwj.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xwj
 * @date 2020/11/10
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StorageFeignClient storageFeignClient;

    /**
     * 创建订单->调用库存服务扣减库存->修改订单状态
     *
     * @param order
     */
    @Override
    @GlobalTransactional(name = "test-create-order", rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("开始新建订单");
        //1、新建订单
        orderMapper.create(order);

        //2、扣减库存
        log.info("开始调用减库存服务");
        CommonResult result = storageFeignClient.decrease(order.getProductId(), order.getCount());
        log.info("结束调用减库存服务");
        if (result.getCode().equals(ResultCode.SUCCESS.getCode())) {
            //3、修改订单状态
            log.info("修改订单状态开始");
            orderMapper.update(order.getUserId(), 0);
            log.info("修改订单状态结束");
        } else {
            throw new RuntimeException("库存不足");
        }
        log.info("订单结束");
    }
}
